#include "myLs.h"

int myLs(char *argv[]){
    // ./ll dir 
    // 打开目录流
    DIR* pdir = opendir(argv[1]);
    ERROR_CHECK(pdir, NULL, "opendir");

    // 遍历目录流
    errno = 0;
    while((pdirent = readdir(pdir)) != NULL) {
        // 获取文件信息
        char buf[256];
        sprintf(buf, "%s/%s", argv[1], pdirent->d_name);
        int ret = stat(buf, &statbuf);
        ERROR_CHECK(ret, -1, "stat");
        // 打印文件的类型
        switch(pdirent->d_type) {
        case DT_BLK: printf("b"); break;
        case DT_CHR: printf("c"); break;
        case DT_DIR: printf("d"); break;
        case DT_FIFO: printf("p"); break;
        case DT_LNK: printf("l"); break;
        case DT_REG: printf("-"); break;
        case DT_SOCK: printf("s"); break;
        default:     printf("u"); break;
        }

        // 打印权限
        for(int i = 0; i < 3; ++i) {
            int m = (statbuf.st_mode >> 3 * (2 - i)) & 0x7;
            switch(m) {
            case 0: printf("---"); break;
            case 1: printf("--x"); break;
            case 2: printf("-w-"); break;
            case 3: printf("-wx"); break;
            case 4: printf("r--"); break;
            case 5: printf("r-x"); break;
            case 6: printf("rw-"); break;
            case 7: printf("rwx"); break;
            }
        }
        
        printf(" %.2ld %s %s %7ld ", 
               statbuf.st_nlink,
               pwd->pw_name,
               grp->gr_name,
               statbuf.st_size);
        
        // 打印时间
        printf("%.4d/%.2d/%.2d %.2d:%.2d:%.2d ",
               tim->tm_year +1900,
               tim->tm_mon +1,
               tim->tm_mday,
               tim->tm_hour,
               tim->tm_min,
               tim->tm_sec);
            

        // 打印名字
        printf("%s\n", pdirent->d_name);
    }
    
    if (errno) {
        perror("readdir");
        closedir(pdir);
        exit(1);
    }
    // 关闭目录流
    closedir(pdir);

    return 0;
}


